import {
  cadAppLog
} from '@amcax/base'
import {
  userEvents
} from '@app-cad/module';
import { MARK_EVENT } from '@app-cad/common/Constants';
import { markManager } from '@app-cad/common/managers/MarkManager';
import { Mark } from '@app-cad/types';
import { Avatar } from 'antd';
import { HTMLAttributes, useEffect, useRef, useState } from 'react';
import { VscClose, VscChromeMinimize } from 'react-icons/vsc';
import { MarkComponentOrigin } from '.';

export default function MarksItem({
  mark,
  onClose,
  source = MarkComponentOrigin.Panel,
  ...rest
}: {
  mark: Mark;
  onClose?: VoidFunction;
  source?: MarkComponentOrigin;
} & HTMLAttributes<HTMLDivElement>) {
  const itemRef = useRef<HTMLDivElement>(null);
  const [selectedMark, setSelectedMark] = useState<Mark>();
  const [user, setUser] = useState<any>();

  useEffect(() => {
    setUser(markManager.getUserByMark(mark));
    registerEvents();
    return () => {
      unregisterEvents();
    };
  }, []);

  const registerEvents = () => {
    if (source === MarkComponentOrigin.Panel) {
      userEvents.on(MARK_EVENT.MARK_SELECTED, (mark) => {
        cadAppLog('[debug]MARK_SELECTED', mark);
        setSelectedMark(mark);
        scrollView();
      });
    }
  };
  const unregisterEvents = () => {
    userEvents.off(MARK_EVENT.MARK_SELECTED);
  };

  const scrollView = () => {
    // if (itemRef.current) {
    //   itemRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    // }
  };

  const formatTime = (time: number) => {
    const date = new Date(time);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  };

  const handleDelete = async (mark: Mark) => {
    await markManager.removeMark(mark);
  };

  const showName = (values: string) => {
    if (!values) return '';
    let Chineseflag = false;
    const valArray = values.split('');
    let result;
    for (let i = 0; i < valArray.length; i++) {
      // eslint-disable-next-line no-control-regex
      if (valArray[i].match(/[^\x00-\xff]/gi) != null) {
        Chineseflag = true;
        result = valArray[i];
        break;
      }
    }
    if (Chineseflag) {
      return result;
    } else {
      if (values.length > 2) return values.slice(0, 2);
      return values;
    }
  };

  return (
    <div
      id={markManager.getMarkUnionId(mark)}
      ref={itemRef}
      className={`mark-item ${selectedMark != null && markManager.getMarkUnionId(selectedMark) === markManager.getMarkUnionId(mark) ? 'selected' : ''}`}
      {...rest}>
      <div className='item-header'>
        <div className='user-info'>
          <Avatar
            size='small'
            style={{ backgroundColor: '#f56a00' }}
            src={user?.avatar}>
            {showName(user?.nickname)}
          </Avatar>
          {user?.nickname}
        </div>
        {source === MarkComponentOrigin.Panel ? (
          <VscClose
            className='close-btn cursor-pointer'
            onClick={() => {
              if (onClose) {
                onClose();
              } else {
                handleDelete(mark);
              }
            }}
          />
        ) : (
          <VscChromeMinimize
            className='close-btn cursor-pointer'
            onClick={() => {
              if (onClose) {
                onClose();
              } else {
                handleDelete(mark);
              }
            }}
          />
        )}
      </div>
      <div className='item-content'>
        <div className='mark-model-name'>{mark.name || '未知名称'}</div>
        <div className='text'>{mark.text || '未知内容'}</div>
        <div className='time'>{formatTime(mark.createdTime) || '未知时间'}</div>
      </div>
    </div>
  );
}
